use tauri::menu::{Menu, MenuItem, PredefinedMenuItem};
use tauri::{
    tray::{TrayIconBuilder, TrayIconEvent},
    AppHandle, Emitter, Manager, WindowEvent,
};

// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

#[tauri::command]
fn create_new_file(app: AppHandle) -> Result<(), String> {
    // 这里可以添加创建新文件的逻辑
    // 例如：打开一个新的编辑器窗口或在当前窗口创建新文件
    let window = app
        .get_webview_window("main")
        .ok_or("Main window not found")?;

    // 聚焦到主窗口
    window.show().map_err(|e| e.to_string())?;
    window.set_focus().map_err(|e| e.to_string())?;

    // 发送事件到前端，通知创建新文件
    app.emit("new-file", {}).map_err(|e| e.to_string())?;

    Ok(())
}

fn create_tray(app: &AppHandle) -> tauri::Result<()> {
    let new_file_item = MenuItem::with_id(app, "new_file", "新建文件", true, None::<&str>)?;
    let separator = PredefinedMenuItem::separator(app)?;
    let quit_item = MenuItem::with_id(app, "quit", "退出", true, None::<&str>)?;

    let menu = Menu::with_items(app, &[&new_file_item, &separator, &quit_item])?;

    let tray = TrayIconBuilder::new()
        .menu(&menu)
        .icon(app.default_window_icon().unwrap().clone())
        .tooltip("青笺编辑器")
        .on_menu_event(move |app, event| match event.id.as_ref() {
            "new_file" => {
                if let Err(e) = create_new_file(app.clone()) {
                    eprintln!("创建新文件失败: {}", e);
                }
            }
            "quit" => {
                app.exit(0);
            }
            _ => {}
        })
        .on_tray_icon_event(|tray, event| {
            if let TrayIconEvent::Click {
                button: tauri::tray::MouseButton::Left,
                ..
            } = event
            {
                let app = tray.app_handle();
                if let Some(window) = app.get_webview_window("main") {
                    let _ = window.show();
                    let _ = window.set_focus();
                }
            }
        })
        .build(app);

    match tray {
        Ok(_) => Ok(()),
        Err(e) => Err(e),
    }
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_http::init())
        .plugin(tauri_plugin_fs::init())
        .plugin(tauri_plugin_opener::init())
        .plugin(tauri_plugin_dialog::init())
        .invoke_handler(tauri::generate_handler![greet, create_new_file])
        .setup(|app| {
            // 创建系统托盘
            create_tray(app.handle())?;
            Ok(())
        })
        .on_window_event(|window, event| {
            if let WindowEvent::CloseRequested { api, .. } = event {
                // 阻止窗口关闭，而是隐藏到系统托盘
                window.hide().unwrap();
                api.prevent_close();
            }
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
